package org.finesys.chat.core.base.document.source;

import org.finesys.chat.core.base.document.Metadata;
import org.finesys.common.core.util.ValidationUtil;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;

public class URLSource implements DocumentSource {

    private final URL url;

    public URLSource(URL url) {
        this.url = ValidationUtil.ensureNotNull(url, "URL");
    }

    @Override
    public InputStream inputStream() throws IOException {
        URLConnection urlConnection = this.url.openConnection();
        return urlConnection.getInputStream();
    }

    @Override
    public Metadata metadata() {
        return Metadata.from("url", this.url.toString());
    }


    public static URLSource from(URL url) {
        return new URLSource(url);
    }

    public static URLSource from(String url) {
        try {
            return new URLSource(new URL(url));
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    public static URLSource from(URI uri) {
        try {
            return from(uri.toURL());
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }
}
